﻿Imports System.Linq
Imports Aricie.DNN.Entities
Imports Aricie.DNN.UI.Attributes
Imports DotNetNuke.UI.WebControls

Namespace Aricie.DNN.Services.Url.FriendlyUrl
    <Serializable()> _
    Public Class QueryStringUrlGroup
        Inherits VariableUrlGroup

        <SortOrder(0)> _
        <ExtendedCategory("MainSettings")> _
        Public Property QueryStringName() As String = ""

        <SortOrder(0)> _
        <ExtendedCategory("MainSettings")> _
        Public Property ValidValues As New EnabledFeature(Of List(Of String))


        Protected Overrides Function GetRawVariable(ByVal writer As UrlRewriteContext) As GroupRewriteResult
            Dim toReturn As New GroupRewriteResult
            Dim queryValue As String = Nothing
            Dim queryParam As UrlParam = UrlParam.FromSyntax(Me._QueryStringName)
            If writer.RewriteInput.QueryStringValues.TryGetValue(queryParam, queryValue) Then
                If ValidValues.Enabled AndAlso Not ValidValues.Entity.Any(Function(strCandidate) strCandidate.ToLowerInvariant() = queryValue.ToLowerInvariant()) Then
                    Throw New ApplicationException(String.Format("Unvalid query string value {0} for parameter {1}", queryValue, _QueryStringName))
                End If
                toReturn.ConsumedParameters(queryParam) = True
                If Me.RewriteType = RewriteType.None Then
                    toReturn.RewriteValue = String.Empty
                Else
                    toReturn.RewriteValue = queryValue
                End If
                writer.ParamsUsage(queryParam) = ParamState.Used
            End If
            Return toReturn
        End Function


        Protected Overrides Function GetName() As String
            Return Me.QueryStringName
        End Function
    End Class
End Namespace

